<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >

      <el-form-item label="车型" prop="carType">
        <el-input
          v-model="queryParams.carType"
          placeholder="请输入车型"
          clearable
          class="!w-240px"/>
      </el-form-item>
      <el-form-item label="收款状态" prop="receiptStatus">
        <el-select
          v-model="queryParams.receiptStatus"
          placeholder="请选择收款状态"
          clearable
          class="!w-240px"
        >
          <el-option label="未收款" value="1"/>
          <el-option label="部分收款" value="4"/>
          <el-option label="已收款" value="3"/>
        </el-select>
      </el-form-item>

      <el-form-item label="渠道名称" prop="channelName">
        <el-select
          v-model="queryParams.channelName"
          placeholder="请选择渠道"
          clearable
          class="!w-240px"
        >
          <el-option label="车妈妈" value="车妈妈"/>
          <el-option label="玖达" value="玖达"/>
          <el-option label="人保财险" value="人保财险"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          plain-->
        <!--          @click="openForm('create')"-->
        <!--          v-hasPermi="['dispatch:receipt:create']"-->
        <!--        >-->
        <!--          <Icon icon="ep:plus" class="mr-5px" /> 新增-->
        <!--        </el-button>-->
        <!--        <el-button-->
        <!--          type="success"-->
        <!--          plain-->
        <!--          @click="handleExport"-->
        <!--          :loading="exportLoading"-->
        <!--          v-hasPermi="['dispatch:receipt:export']"-->
        <!--        >-->
        <!--          <Icon icon="ep:download" class="mr-5px" /> 导出-->
        <!--        </el-button>-->
      </el-form-item>
    </el-form>

    <el-row class="mt-15px">
      <el-col>
        <el-button @click="handleBatchReceipt" type="primary">批量确认收款</el-button>
        <el-button @click="handleBatchCancelReceipt" type="danger">批量撤销收款</el-button>

        <el-button @click="handleBatchReconciliation" type="primary">批量对账</el-button>
        <el-button @click="handleBatchCancelReconciliation" type="danger">批量撤销对账</el-button>
      </el-col>
    </el-row>

  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" ref="multipleTableRef" @selection-change="handleSelectionChange"
              :data="list" border :stripe="true" :show-overflow-tooltip="true">


      <el-table-column type="selection" fixed="left" width="40"/>
      <el-table-column label="操作" width="60" fixed="left" align="center" prop="payStatus">
        <template #default="scope">
          <el-popover :visible="popoverVisible == scope.row.id" placement="top" :width="100">

            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="primary"
                  @click="handleReceipt(scope.row)"
                  v-if="scope.row.unreceiptAmount>0"
                  v-hasPermi="['dispatch:payment:update']"
                >
                  确认收款
                </el-button>
              </el-col>
            </el-row>

            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  style="margin: 0"
                  type="warning"
                  @click="cancelReceipt(scope.row.id)"
                  v-hasPermi="['dispatch:payment:update']"
                  v-if="scope.row.receiptStatus != 1"
                >
                  撤销收款
                </el-button>
              </el-col>
            </el-row>

            <!--            <el-row class="mb-8px">-->
            <!--              <el-col :span="24">-->
            <!--                <el-button-->
            <!--                  link-->
            <!--                  type="danger"-->
            <!--                  @click="handleDelete(scope.row.id)"-->
            <!--                  v-hasPermi="['dispatch:payment:delete']"-->
            <!--                  v-if="scope.row.receiptStatus ==1"-->
            <!--                >-->
            <!--                  驳回-->
            <!--                </el-button>-->
            <!--              </el-col>-->
            <!--            </el-row>-->

            <!--            <el-row class="mb-8px">-->
            <!--              <el-col :span="24">-->
            <!--                <el-button-->
            <!--                  link-->
            <!--                  type="danger"-->
            <!--                  @click="handleCancelCheck(scope.row.id)"-->
            <!--                  v-hasPermi="['dispatch:payment:delete']"-->
            <!--                  v-if="scope.row.checkStatus ==3"-->
            <!--                >-->
            <!--                  取消对账-->
            <!--                </el-button>-->
            <!--              </el-col>-->
            <!--            </el-row>-->


            <div class="popoverCloseBtn" @click="closePopover()">关闭</div>
            <template #reference>
              <img src="@/assets/imgs/more_edit.png" class="linkBtn"
                   @click="handleRightClick(scope.row.id)"
                   @contextmenu.prevent="handleRightClick(scope.row.id)"/>
            </template>
          </el-popover>
        </template>
      </el-table-column>


      <!--      <el-table-column label="订单编号" align="center" prop="id" />-->
      <!--      <el-table-column label="派单订单no" align="center" prop="dispatchOrderNo" />-->
      <el-table-column label="订单渠道" fixed="left" width="90" prop="channelName"/>
      <!--      <el-table-column label="门店名称" align="center" prop="storeName" />-->
      <!--      <el-table-column label="服务门店" align="center" prop="storeId" />-->
      <!--      <el-table-column label="派单订单" align="center" prop="dispatchOrderId" />-->


      <!--      <el-table-column label="开启状态" align="center" prop="status" />-->
      <!--      <el-table-column label="排序" align="center" prop="sort" />-->
      <el-table-column label="车型" width="180" prop="carType"/>
      <el-table-column label="收款金额" width="90" prop="receiptPrice"/>
      <el-table-column label="已收金额" width="90" prop="receiptAmount"/>
      <el-table-column label="未收金额" width="90" prop="unreceiptAmount"/>
      <!--      <el-table-column label="优惠金额" align="center" prop="discountPrice" />-->

      <el-table-column label="收款状态" align="center" fixed="left" width="90" prop="receiptStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_RECEIPT_STATUS" :value="scope.row.receiptStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="对账状态" align="center" width="90" prop="checkStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_CHECK_STATUS" :value="scope.row.checkStatus"/>
        </template>
      </el-table-column>
      <el-table-column
        label="对账时间"
        align="center"
        prop="checkDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="订单编号" align="center" width="180px" prop="no"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>


  <el-dialog
    v-model="dialogReceiptVisible"
    title="确认收款"
    width="20%"
  >
    <el-input v-model="handleReceiptData.receiptAmount"/>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogReceiptVisible = false">取消</el-button>
        <el-button type="primary" @click="comfirmReceipt"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>


  <!-- 表单弹窗：添加/修改 -->
  <ReceiptForm ref="formRef" @success="getList"/>
</template>

<script setup lang="ts">
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {DICT_TYPE} from '@/utils/dict'
import {ReceiptApi, ReceiptVO} from '@/api/dispatch/receipt'
import ReceiptForm from './ReceiptForm.vue'
import {PaymentApi} from "@/api/dispatch/payment";
import {ElLoading, ElMessage} from "element-plus";

/** 派单收款单 列表 */
defineOptions({name: 'DispatchReceipt'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中

const list = ref<ReceiptVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  dispatchOrderNo: undefined,
  storeName: undefined,
  storeId: undefined,
  ids:[],
  dispatchOrderId: undefined,
  no: undefined,
  remark: undefined,
  status: undefined,
  sort: undefined,
  carType: undefined,
  receiptPrice: undefined,
  discountPrice: undefined,
  createTime: [],
  receiptStatus: undefined,
  receiptAmount: undefined,
  unreceiptAmount: undefined,
  checkStatus: undefined,
  checkDate: [],
  channelName: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中



/**
 * 批量收款
 */
const handleBatchReceipt = async () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要收款的订单');
    return;
  }
  let loading;
  try {

    await message.delConfirm('是否确认批量收款？', '批量收款')

    loading = ElLoading.service({
      lock: true,
      text: '批量收款中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    await ReceiptApi.handleBatchReceipt(multipleSelection.value)
    message.success(t('处理成功'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    multipleTableRef.value!.clearSelection()
    loading.close()
    popoverVisible.value = null;
  }
}


/**
 * 批量撤销对账
 */
const handleBatchCancelReconciliation = async () => {


  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要撤销对账的订单');
    return;
  }
  let loading;
  try {

    await message.confirm('是否确认批量撤销对账？', '批量撤销对账')

    loading = ElLoading.service({
      lock: true,
      text: '撤销对账中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    await ReceiptApi.handleBatchCancelReconciliation(multipleSelection.value)
    message.success(t('处理成功'))
    await getList()
  } catch {
  } finally {
    multipleTableRef.value!.clearSelection()
    loading.close()
    popoverVisible.value = null;
  }
}

/**
 * 批量对账
 */
const handleBatchReconciliation = async () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要对账的订单');
    return;
  }
  let loading;
  try {

    await message.confirm('是否确认批量对账？', '批量对账')

    loading = ElLoading.service({
      lock: true,
      text: '批量对账中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    await ReceiptApi.handleBatchReconciliation(multipleSelection.value)
    message.success(t('处理成功'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    multipleTableRef.value!.clearSelection()
    loading.close()
    popoverVisible.value = null;
  }
}

/**
 * 批量撤销付款
 */
const handleBatchCancelReceipt = async () => {

  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要撤销的订单');
    return;
  }
  let loading;
  try {

    await message.delConfirm('是否确认批量撤销收款？', '撤销收款')

    loading = ElLoading.service({
      lock: true,
      text: '撤销收款中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    await ReceiptApi.handleBatchCancelReceipt(multipleSelection.value)
    message.success(t('处理成功'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    multipleTableRef.value!.clearSelection()
    loading.close()
    popoverVisible.value = null;
  }
}


/**
 * 确认收款
 */
const dialogReceiptVisible = ref(false)
const handleReceiptData = reactive({
  id: undefined,
  receiptAmount: undefined
})

const handleReceipt = async (row) => {


  if (row.unreceiptAmount == 0) {
    message.error('该收款单已全部收款')
    return;
  }

  handleReceiptData.id = row.id;
  dialogReceiptVisible.value = true;
  handleReceiptData.receiptAmount = row.unreceiptAmount;
}

const comfirmReceipt = async () => {
  try {
    await message.confirm('是否确认收款？', '确认收款')
    await ReceiptApi.handleReceipt(handleReceiptData)
    message.success(t('确认收款成功'))
    await getList()
    dialogReceiptVisible.value = false;
  } catch {
  } finally {
    popoverVisible.value = null;
  }
}


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ReceiptApi.getReceiptPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}


// 撤销收款
const cancelReceipt = async (id) => {
  try {
    await message.confirm('是否确认撤销收款？', '撤销收款')
    await ReceiptApi.cancelReceipt(id)
    message.success(t('撤销成功'))
    await getList()
  } catch {
  } finally {
    popoverVisible.value = null;
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.ids= [];
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ReceiptApi.deleteReceipt(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}


const popoverVisible = ref();
const multipleTableRef = ref()
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const closePopover = async () => {
  popoverVisible.value = null;
}
const handleRightClick = (id) => {
  popoverVisible.value = id;
};

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ReceiptApi.exportReceipt(queryParams)
    download.excel(data, '派单收款单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const route = useRoute();
/** 初始化 **/
onMounted(() => {

  //初始化ids
  queryParams.ids = null;

  let query = route.query;
  if (query.doType == 'query') {
    queryParams.ids = query.data;
  }

  getList()
})
onActivated(() => {
  //初始化ids
  queryParams.ids = null;

  let query = route.query;
  if (query.doType == 'query') {
    queryParams.ids = query.data;
  }

  getList()
})
</script>
